package org.base.generator.modules.code.service;
import org.apache.commons.io.IOUtils;
import org.base.dao.common.Page;
import org.base.generator.modules.code.mapper.GeneratorDao;
import org.base.generator.utils.GenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 */
@Service
public class GeneratorServiceImpl {
	@Autowired
	private GeneratorDao generatorDao;
	
	public Page<Map<String,Object>> findPage(Page<Map<String,Object>> page) {
		Map<String,Object> condition = page.getCondition();
		if(Objects.isNull(condition))
			condition = new HashMap<>();
		page.setCondition(condition);
		List<Map<String, Object>> records = generatorDao.queryList(page);
		page.setRecords(records);
		return page;
	}

	public Map<String, String> queryTable(String tableName) {
		return generatorDao.queryTable(tableName);
	}

	public List<Map<String, String>> queryColumns(String tableName) {
		return generatorDao.queryColumns(tableName);
	}

	public byte[] generatorCode(String[] tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		for(String tableName : tableNames){
			//查询表信息
			Map<String, String> table = queryTable(tableName);
			//查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			//生成代码
			GenUtils.generatorCode(table, columns, zip);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
}
